<template>
  <div class="archives-detail-page">
    <div class="container">
      <div class="detail-header">
        <div class="detail-header-title">
          <div class="name fw-title">{{ archivesData.name }}</div>
          <div class="labels">
            <el-tag type="danger">{{
              ARCHIVES_TYPE_NAMES[archivesData.archivesType] }}</el-tag>
            <span class="state">{{ ARCHIVES_STATE_NAMES[archivesData.state] }}</span>
          </div>
        </div>
        <div class="back"><el-button type="text" size="small" @click="backArchives">返回</el-button></div>
      </div>
      <div class="base-info">
        <div class="base-info-title fw-title fz-18">基础信息</div>
        <div class="base-info-content">
          <div class="row-wrap single-row">
            <form-item class="form-item" label="火灾分类：" :value="ARCHIVES_FIRE_CLASSIFY_NAMES[archivesData.category]" />
          </div>
          <div class="row-wrap">
            <form-item class="form-item" label="起火对象：" :value="archivesData.fireName" />
            <form-item class="form-item" label="起火地点：" :value="formatAddress(archivesData.fireAddress)" />
            <form-item class="form-item" label="是否爆炸：" :value="ARCHIVES_EXPLODE_NAMES[archivesData.isExplode]" />
          </div>
          <div class="row-wrap">
            <form-item class="form-item" label="起火天气：" :value="archivesData.weather" />
            <form-item class="form-item" label="详细地址：" :value="archivesData.address" />
          </div>
          <div class="row-wrap single-row">
            <form-item class="form-item" label="简单描述：" :value="archivesData.remark" />
          </div>
          <div class="row-wrap">
            <form-item class="form-item" label="承办单位：" :value="archivesData.doOrg" />
          </div>
          <div class="row-wrap">
            <form-item class="form-item" label="主办人：" :value="archivesData.doPersonName" />
            <form-item class="form-item" label="报警时间：" :value="archivesData.callTime" />
            <form-item class="form-item" label="出警车辆：" :value="archivesData.doCars" />
          </div>
          <div class="row-wrap">
            <form-item class="form-item" label="协办人：" :value="archivesData.doOtherPersonName" />
            <form-item class="form-item" label="出警时间：" :value="archivesData.goTime" />
            <form-item class="form-item" label="出警人数：" :value="archivesData.doPersonCount" />
          </div>
        </div>
      </div>
      <div class="line"></div>
      <div class="case-time-axis">
        <div class="case-time-axis-head">
          <div class="time-axis-head-title fw-title  fz-18">案件证据链</div>
          <div class="time-axis-head-switch" @click="onChangeTimeAxis"><i class="icon el-icon-sort"></i></div>
        </div>
        <div class="time-axis">
          <TimeAxisArrow v-if="isClickModule" class="line" :module-arr="ModuleArr"
            @timelineItemClick="showCurrentModule" />
          <div v-show="isClickModule" class="time-axis-content a">
            <div class="item line">
              <div class="title fw-title">
                <span>{{ currentModuleObj.name }}</span>
                <el-button v-if="moduleObj[currentModuleObj.value] && showFileTimeAxis(currentModuleObj.value)"
                  size="mini" type="primary" icon="el-icon-plus"
                  @click="handleAdd(moduleObj[currentModuleObj.value])">新增</el-button>
              </div>
              <TimeAxisContentList v-if="moduleObj[currentModuleObj.value] && !showFileTimeAxis(currentModuleObj.value)"
                @add-file="handleAdd" :dictId="currentModuleObj.value" :moduleObj="moduleObj" :isCenter="isClickModule" />
              <TimeAxisContentFile v-else
                :timeAxisList="fileTimeAxisList((moduleObj[currentModuleObj.value] || {}).mapList)"
                :currentModuleObj="currentModuleObj" :isCenter="isClickModule" :moduleObj="moduleObj" />
            </div>
          </div>
          <div v-show="!isClickModule" class="time-axis-content b">
            <div class="item line" v-for="moduleItem in moduleList" :key="moduleItem.value">
              <div class="title fw-title">
                <span>{{ moduleItem.name }}</span><el-button
                  v-if="moduleObj[moduleItem.value] && showFileTimeAxis(moduleItem.value)" size="mini" type="primary"
                  icon="el-icon-plus" @click="handleAdd(moduleObj[moduleItem.value])">新增</el-button>
              </div>
              <TimeAxisContentList v-if="moduleObj[moduleItem.value] && !showFileTimeAxis(moduleItem.value)"
                @add-file="handleAdd" :dictId="moduleItem.value" :moduleObj="moduleObj" :isCenter="isClickModule" />
              <TimeAxisContentFile v-else :timeAxisList="fileTimeAxisList((moduleObj[moduleItem.value] || {}).mapList)"
                :currentModuleObj="moduleItem" :isCenter="isClickModule" :moduleObj="moduleObj" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-image v-show="false" ref="elImage" :preview-src-list="srcList" />
    <H5Iframe v-model="iframeVisible" :dictId="dictId" :noticeId="currentRow.noticeId" :archivesId="currentRow.archivesId"
      :keyId="currentKeyId" :currentIndex="currentIndex" @message="receiveMessage" />
  </div>
</template>
<script>
import FormItem from '@/components/FormItem/FormItem.vue'
import H5Iframe from '@/components/H5Iframe/H5Iframe.vue'
import TimeAxisArrow from './components/time-axis-arrow.vue'
import TimeAxisContentFile from './components/time-axis-content-file.vue'
import TimeAxisContentList from './components/time-axis-content-list.vue'
import { checkType } from '@/utils/common'
import { ARCHIVES_STATE_NAMES, ARCHIVES_TYPE_NAMES, ARCHIVES_FIRE_CLASSIFY_NAMES, ARCHIVES_EXPLODE_NAMES } from '@/const/archives'
import { getDetail as GetModuleDetail } from '@/api/archives/notice'
import { get as GetArchivesDetail } from '@/api/archives/archives'
import { getModule as GetModuleList } from '@/api/archives/module'
import { MODULE_DICTID, MODULE_ID } from '@/const/modules/index.js'

export default {
  name: 'ArchivesDetail',
  components: { FormItem, H5Iframe, TimeAxisArrow, TimeAxisContentList, TimeAxisContentFile },
  data() {
    return {
      MODULE_DICTID,
      ARCHIVES_STATE_NAMES,
      ARCHIVES_TYPE_NAMES,
      ARCHIVES_FIRE_CLASSIFY_NAMES,
      ARCHIVES_EXPLODE_NAMES,
      moduleList: [],
      ModuleArr: [],
      archivesData: {},
      moduleObj: {},
      currentModuleObj: {},
      iframeVisible: false,
      dictId: 0,
      currentRow: {
        noticeId: 0
      },
      currentIndex: -1,
      pdfDownload: false,
      isEdit: true,
      isClickModule: true,
      currentKeyId: 0,
      srcList: []
    }
  },
  computed: {
    formatAddress() {
      return address => {
        if (!address || !address.length) return '';
        if (checkType(address) === 'string') {
          return address.split(',')[2]
        } else if (checkType(address) === 'array') {
          return address[2];
        }
      };
    },
    showFileTimeAxis() {
      const { specialty, sketch, evidence, photo, video } = MODULE_DICTID
      return (dictId) => {
        return [specialty, sketch, evidence, photo, video].includes(parseInt(dictId))
      }
    },
    fileTimeAxisList() {
      return (list) => {
        const filteredFiles = (list || []).filter(item => item?.fileList?.length);
        const sortedFiles = filteredFiles.flatMap(item => item.fileList).sort((a, b) => a.time - b.time);
        return sortedFiles;
      }
    },
    currentModule() {
      const currentDictId = this.dictId;
      const currentModule = Object.entries(MODULE_DICTID).find(([key, value]) => value == currentDictId);
      const [moduleName,] = currentModule;
      const moduleId = MODULE_ID[currentDictId]
      return { moduleName, moduleId }
    },
  },
  watch: {
    '$route.query.archivesId': {
      handler(val) {
        if (val) {
          this.init()
        }
      }
    }
  },
  deactivated() {
    this.iframeVisible = false
  },
  created() {
    this.init()
  },
  methods: {
    init(type) {
      let lastHaveFileModule = {}
      GetModuleList(this.$route.query.archivesId).then(res => {
        let data = res.data
        this.moduleList = data

        // 需要合并的 value 数组
        const mergeValues = ["5", "6"];

        // 创建一个新的数组来存储修改后的步骤
        const modifiedSteps = [];

        // 初始化一个变量用于记录当前合并的步骤
        let mergedStep = null;

        // 遍历原始数组
        for (let i = 0; i < data.length; i++) {
          const currentStep = data[i];

          // 判断是否需要合并当前步骤
          if (mergeValues.includes(currentStep.value)) {
            // 如果需要合并，将当前步骤的属性值添加到合并的步骤中
            if (!mergedStep) {
              mergedStep = {
                moduleStatus: [currentStep.moduleStatus],
                name: [currentStep.name],
                remark: [currentStep.remark],
                value: [currentStep.value],
                noticeId: [currentStep.noticeId],
                fileNum: [currentStep?.fileNum || 0],
              }; // 克隆当前步骤作为合并的步骤的初始值
            } else {
              mergedStep.moduleStatus.push(currentStep.moduleStatus);
              mergedStep.name.push(currentStep.name);
              mergedStep.remark.push(currentStep.remark);
              mergedStep.value.push(currentStep.value);
              mergedStep.noticeId.push(currentStep.noticeId);
              mergedStep.fileNum.push(currentStep?.fileNum || 0);
            }
          } else {
            // 如果不需要合并，将合并的步骤添加到修改后的步骤数组中，并重置合并的步骤为 null
            if (mergedStep) {
              modifiedSteps.push(mergedStep);
              mergedStep = null;
            }

            // 直接将当前步骤添加到修改后的步骤数组中
            modifiedSteps.push(currentStep);
          }

          if (currentStep.fileNum > 0) {
            lastHaveFileModule = currentStep
          }
          if (Object.keys(this.currentModuleObj).length > 0 && this.currentModuleObj.value == currentStep.value) {
            this.currentModuleObj = currentStep
          }
        }

        // 检查最后一个合并的步骤是否需要添加到修改后的步骤数组中
        if (mergedStep) {
          modifiedSteps.push(mergedStep);
        }

        if (Object.keys(this.currentModuleObj).length == 0) {
          this.currentModuleObj = lastHaveFileModule
        }

        this.ModuleArr = modifiedSteps
      })
      GetArchivesDetail(this.$route.query.archivesId).then(res => {
        this.archivesData = res.data
      })
      GetModuleDetail({ archivesId: this.$route.query.archivesId }).then(res => {
        let rows = res.rows
        let obj = {}

        rows.forEach(item => {
          obj[item.dictId] = item
        })
        this.moduleObj = obj
      })
    },
    backArchives() {
      this.$router.push({
        path: '/Marchives/archives'
      })
    },
    receiveMessage(event) {
      const eventName = event.data
      if (eventName == 'cancel') {
        this.iframeVisible = false
        this.currentIndex = ''
      } else if (eventName == 'success') {
        this.$message.success('操作成功')
        if (this.$route.query.archivesId) {
          this.init()
        }
        this.iframeVisible = false
        this.currentIndex = ''
      }

      // data是子页面发送的数据，没有类型限制
    },
    handleAdd(row, index = '') {
      this.dictId = row.dictId
      const key = `${this.currentModule.moduleId}`
      this.currentKeyId = index == '' && index !== 0 ? 0 : row.mapList[index][key]

      this.currentRow = row
      this.currentIndex = index
      this.iframeVisible = true
    },
    onChangeTimeAxis() {
      this.isClickModule = !this.isClickModule
    },
    showCurrentModule(item) {
      this.currentModuleObj = item
    },
  }
}
</script>
<style scoped lang="scss">
@import '@/assets/styles/element-variables.scss';

.fw-title {
  font-weight: bold;
}

.fz-18 {
  font-size: 18px;
}

.archives-detail-page {
  // padding: 20px;
  // background: #f0f2f5;
  height: calc(100% - 58px);
  overflow: hidden;

  .container {
    background-color: #fff;
    padding: 24px;
    height: 100%;
    overflow: hidden auto;
    border-radius: 8px;

    .line {
      // width: 100%;
      // height: 1px;
      // background-color: 1px solid #E0E0E0;
      border-bottom: 1px solid #E0E0E0;
    }
  }

  .detail-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 26px;

    &-title {
      display: flex;
      align-items: center;

      .name {
        font-size: 18px;
        font-weight: bold;
        color: #333;
        margin-right: 24px;
      }

      .labels {
        span:first-child {
          margin-right: 24px;
        }

        .state {
          color: $--color-danger;
          font-size: 14px;
        }
      }
    }
  }

  .base-info {
    width: 100%;
    margin-bottom: 23px;

    &-title {
      margin-bottom: 18px;
    }

    &-content {
      width: 100%;

      .row-wrap {
        display: flex;
        align-items: flex-start;
        margin-bottom: 10px;

        &.single-row {
          .form-item {
            flex: 1;
          }
        }

        .form-item {
          flex: 33.33334% 0 0;
          padding-right: 12px;
          height: 100%;
          font-size: 16px;
          line-height: 16px;
        }

        ::v-deep .form-item {
          .label {
            min-width: 80px;
          }
        }
      }
    }
  }

  .case-time-axis {
    padding: 24px 0;

    &-head {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .time-axis-head-switch {
        cursor: pointer;
        transition: 0.3s;

        &:hover {
          transform: scale(1.2);
          color: #666;
        }

        .icon {
          transform: rotate(90deg);
          font-weight: bold;
          font-size: 30px;
        }
      }
    }

    .time-axis-steps {
      display: flex;
      flex-wrap: nowrap;
      position: relative;

      .step-item {
        position: relative;
        --arrow-height: 16px;
        --arrow-left-width: 8px;
        --rectangle-width: 156px;
        --arrow-active-color: #004AA5;
        --arrow-color: #e6e6e6;
        // min-width: calc(var(--arrow-left-width) * 2 + var(--rectangle-width));
        flex: calc(var(--arrow-left-width) * 2 + var(--rectangle-width));
        height: 100%;
        margin: 29px 0;
        font-size: 14px;

        &:first-of-type {
          .arrow-container {
            .rectangle {
              border-left: var(--arrow-left-width) solid var(--arrow-color);
            }
          }
        }

        .active {
          --arrow-color: var(--arrow-active-color)
        }

        .special {
          position: absolute;
          top: 50%;
          transform: translateY(-25%);
        }

        .arrow-container {
          height: 100%;
          position: relative;
          display: flex;
          margin-right: var(--arrow-left-width);
          cursor: pointer;
          color: #333;
        }

        .rectangle {
          border-top: var(--arrow-height) solid var(--arrow-color);
          border-bottom: var(--arrow-height) solid var(--arrow-color);
          border-right: var(--rectangle-width) solid var(--arrow-color);
          border-left: var(--arrow-left-width) solid transparent;
        }

        .arrow-right {
          position: absolute;
          top: 0;
          right: calc((var(--arrow-left-width) + var(--rectangle-width)) * -1);
          border-top: var(--arrow-height) solid transparent;
          border-bottom: var(--arrow-height) solid transparent;
          border-right: var(--rectangle-width) solid transparent;
          border-left: var(--arrow-left-width) solid var(--arrow-color);
        }

        .text {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          font-size: 12px;
        }
      }
    }

    .time-axis-content {

      .item {
        padding: 24px 0;
      }

      .title {
        margin-bottom: 6px;

        span {
          margin-right: 14px;
        }
      }
    }
  }

  .time-axis {
    padding-left: 6px;
  }
}
</style>